<!-- 模板详情 -->
<template>
  <div class="template-dialog">
    <!-- <div class="template-menu">
      <span class="template-title">屏幕名称</span>
      <div id="accordion">
        左侧菜单
         <el-tooltip v-for="(data,index) in screenData" :key="data.id" placement="right-start">
          <div slot="content">
            名称: {{ data.name }}<br />
            分辨率: {{ data.width }} * {{ data.height }}
          </div>
          <a @click="doAddActive('Screen', data)"
            href="javascript:;"
            :name="`Screen` + data.id"
            index="0"
            class="addWiget">
              {{ data.name }}
            </a>
          </el-tooltip>
      </div>
    </div> -->
    <div class="template-main">
      <div class="template-condition">
        <el-form :inline="true" ref="editorFormRef" size="small">
          <el-form-item :label="$t('终端名称')" prop="name">
            <el-input
              id="name"
              v-model="deviceName"
              autocomplete="off"
              show-word-limit
              clearable
              style="width: 370px"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item>
            <bs-confirm-button-icon @click.native="doSubmit"></bs-confirm-button-icon>
          </el-form-item>
        </el-form>
      </div>
      <!-- 右键删除菜单 -->
      <!-- <delete-context-menu></delete-context-menu> -->
      <!-- 添加的元素 -->
      <elements></elements>
      <div
        :class="[className]"
        :style="[computedStyle]"
        class="template-main-wrapper"
      >
        <div
          :style="[computedInnerStyle]"
          class="compont"
          id="compont"
          ref="capture"
        ></div>
      </div>
    </div>
    <!-- <div class="template-attr">
      <layout-model :data="attrForm"></layout-model>
    </div> -->
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import Elements from '../../../media/components/TemplateComponents/Elements'
// import DeleteContextMenu from '../../../media/components/TemplateComponents/DeleteContextMenu'
// import LayoutModel from './LayoutModel'
import { TemplateOptions } from '@/mixins/ScreenTemplate.js'
import { deepClone } from '@/utils/index'
import { HashMap } from '@/utils/hashmap'

const templateFormData = {
  X: 0,
  Y: 0,
  W: 0,
  H: 0,
  width: 0,
  height: 0,
  svl: 0
}
export default {
  data() {
    const width = 4000
    const height = 4000
    return {
      twidget: [],
      widgetData: {},
      wrapperWidth: 560,
      wrapperHeight: 560,
      attrForm: deepClone(templateFormData),
      templateOpts: {
        width: width,
        height: height,
      },
      loading: null,
      maxsvl: 3
    }
  },
  mixins: [TemplateOptions],
  props: {
    className: {
      type: String,
      default: '',
    },
    deviceName: {
      type: String,
      default: ''
    },
    deviceIds: {
      type: Array,
      default: () => []
    },
    width: {
      default: 4000
    },
    height: {
      default: 4000
    },
    screenData: {
      default: () => []
    },
    deviceWidgetData: {
      default: () => []
    }
  },
  components: {
    // eslint-disable-next-line vue/no-unused-components
    html2canvas,
    // LayoutModel,
    Elements,
    // DeleteContextMenu
  },
  mounted() {
    this.$nextTick(function () {
      this.twidget = this.deviceWidgetData
      setTimeout(() => {
        this.layoutInit()
      }, 500);
    })
  },
  created() {
    this.$eventBus.$on('changeResolution', this.changeResolution)
    this.$eventBus.$on('changeAttr', this.changeAttr)
    this.initDeviceData()
  },
  beforeDestroy() {
    this.$eventBus.$off('changeResolution')
    this.$eventBus.$off('changeAttr')
  },
  methods: {
    // 保存模板
    async doSubmit() {
      if (this.widgetData.isEmpty()) {
        this.$message.error('请添加组件!')
        return
      }
      let isAnchor = true
      let svlRepeat = true
      let svlMap = new HashMap();
      let repeatValue = 0
      this.widgetData.values().forEach(item => {
        if(svlMap.containsKey(item.svl)) {
          svlRepeat = false
          repeatValue = item.svl ? item.svl : 0
          return
        }
        svlMap.put(item.svl, item.svl)
        if(item.type.indexOf('Screen') >= 0){
          isAnchor = false
          return
        }
      })
      // if(!svlRepeat) {
      //   this.$message.error('音频输出优先级['+repeatValue+']不能重复!')
      //   return
      // }
      if(isAnchor) {
        this.$message.error('请添加屏幕组件!')
        return
      }
      if (this.loading === null) {
        this.loading = this.$loading({ fullscreen: true, text: this.$t('保存中...') })
      }
      setTimeout(() => {
        if (this.loading) {
             this.realCommit()
        }
      }, 1000);
      // this.$emit('save', [])

    },
    realCommit() {
      let _this = this
      html2canvas(this.$refs.capture).then(function (canvas) {
          // var imgUri = canvas.toDataURL('image/png').replace('data:image/png;base64,', '')
          let ids = _this.deviceIds
          let saveData = {}
          saveData.terminalIds = ids
          saveData.width = _this.attrForm.width
          saveData.height = _this.attrForm.height
          saveData.template = _this.widgetData.values().map(item => {
            return {
              ...item,
              svl: item.svl || 0,
              rotate: item.rotate || 0
            }
          }) // 修复不选时svl为空而不为0的情况

          _this.$emit('save', saveData)
          if (_this.loading) {
              _this.loading.close()
              _this.loading = null;
          }
      });
    },
    // 添加组件
    doAddActive(name, itemData) {
      console.log(itemData)
      this.initNeedAddWidgetInfo(name, itemData, this.maxsvl)
      if(this.maxsvl > 0) {
        this.maxsvl = this.maxsvl - 1
      }
    },
    // 更改属性
    async changeAttr(attr, val) {
      let resolution
      var res
      switch(attr){
        // 改X坐标
        case 'xposition':
          this.updateSelectedWidget(val, 1)
          this.attrForm.X = Number(val)
          break
        // 改Y坐标
        case 'yposition':
          this.updateSelectedWidget(val, 2)
          this.attrForm.Y = Number(val)
          break
        // 改宽度
        case 'wid':
          resolution = val + '*' + this.templateOpts.height
          res = await this.doChangeResolution(resolution)
          if(res) {
            this.templateOpts.width = val
          } else {
            this.attrForm.width = this.templateOpts.width
          }
          break
        // 改高度
        case 'hei':
          resolution = this.templateOpts.width + '*' + val
          res = await this.doChangeResolution(resolution)
          if(res) {
            this.templateOpts.height = val
          } else {
            this.attrForm.height = this.templateOpts.height
          }
          break
        case 'svl':
          this.attrForm.svl = Number(val)
          this.updateSelectedWidget(val, 3)
          break
      }
    },
    initDeviceData() {
      this.templateOpts = {
        width: this.width,
        height: this.height
      }
      this.attrForm = {
        ...deepClone(templateFormData),
        width: this.width,
        height: this.height
      }
      this.layoutInit()
    }
  },
  watch:{
    deviceWidgetData(val) {
      this.twidget = val
      this.layoutInit()
      console.log('deviceWidgetData: ', this.twidget)
    }
  },
  computed: {
    computedStyle() {
      let w = this.wrapperWidth
      let h = this.wrapperHeight
      if (typeof w === 'number') {
        w = isNaN(w) ? '' : `${w}px`
      }
      if (typeof h === 'number') {
        h = isNaN(h) ? '' : `${h}px`
      }
      let styles = {}
      if (w) styles.width = w
      if (h) styles.height = h

      return styles
    },
    computedInnerStyle() {
      const {width, height} = this.templateOpts // 现实模版宽高
      console.log(width,height,'width,height')
      let {width: wrapWidth, height: wrapHeight} = this.computedStyle // 容器宽高
      wrapWidth = Number(wrapWidth.replace('px', ''))
      wrapHeight = Number(wrapHeight.replace('px', ''))
      console.log(wrapWidth,wrapHeight,'wrapWidth,wrapHeight')
      let styleWidth;                 // 最终模版在容器的宽
      let styleHeight;                // 最终模版在容器的高
      let ratio;                      // 缩放比

      let wrapRatio = width / height
      if(wrapRatio > 1) {
        ratio = wrapWidth / width
        styleWidth = `${wrapWidth}px`
        styleHeight = `${height * ratio}px`
      }else if(wrapRatio < 1) {
        ratio = wrapHeight / height
        styleWidth = `${width * ratio}px`
        styleHeight = `${wrapHeight}px`
      } else {
        ratio = wrapWidth / width
        styleWidth = `${wrapWidth}px`
        styleHeight = `${wrapHeight}px`
      }
      this.$nextTick(() => {
        this.iwidthPercent = ratio
        this.iheightPercent = ratio
        // 舞台已初始化好
        // 开始塞入组件
        this.layoutInit()
      })

      return {
        width: styleWidth,
        height: styleHeight
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.addWiget {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-bottom: 1px solid $bg-e9;
  height: 48px;
}
.addWiget:hover {
  background-color: $defaultBlue;
  color:#fff !important;
}
.notclick {
  display: flex;
  justify-content: space-around;
  align-items: center;
  // text-decoration: line-through;
  border-bottom: 1px solid $bg-e9;
  height: 48px;
  pointer-events: none;
  filter: grayscale(10%);
  color: #ddd;
}
.template-main{
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
.template-condition{
  margin: 20px auto;
}
.template-main-wrapper {
  position: relative;
  overflow: hidden;

  .compont {
    background: $bg-f4;
  }
}
</style>
